package com.example.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.reggie.common.exception.CustormException;
import com.example.reggie.dto.SetmealDto;
import com.example.reggie.entity.Setmeal;
import com.example.reggie.entity.SetmealDish;
import com.example.reggie.mapper.SetmealMapper;
import com.example.reggie.service.SetmealDishService;
import com.example.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;

    @Transactional

    @Override
    public boolean saveWithDish(SetmealDto setmealDto) {
        this.save(setmealDto);

        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes();
       setmealDishList= setmealDishList.stream().map(item->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        return setmealDishService.saveBatch(setmealDishList);
    }
@Transactional
    @Override
    public boolean removeSetmealWithDish(List<Long> ids) {
    LambdaQueryWrapper<Setmeal> setmealQuery = new LambdaQueryWrapper<>();
    setmealQuery.in(Setmeal::getId,ids)
               .eq(Setmeal::getStatus,1);
    int count = this.count(setmealQuery);
    if(count>0){
        throw new CustormException("套餐在售，不能删除");
//        return false;
    }

     this.removeByIds(ids);

    LambdaQueryWrapper<SetmealDish> setmealDishQuery = new LambdaQueryWrapper<>();
    setmealDishQuery.in(SetmealDish::getDishId,ids);
   return setmealDishService.remove(setmealDishQuery);

    }
}
